
package www.wmx.com.xssc.util;


import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import www.wmx.com.xssc.domain.doc.fj.RbtScfjMb;
import www.wmx.com.xssc.domain.doc.fj.ZtComUploadFile;
import www.wmx.com.xssc.domain.doc.fj.ZtComUploadFileOrigin;
import www.wmx.com.xssc.domain.doc.jcyjj.RbtKjjlJcyjjFjxx;
import www.wmx.com.xssc.domain.doc.jcyjj.RbtKjjlJcyjjJbxx;
import www.wmx.com.xssc.domain.doc.jsfmj.RbtKjjlJsfmjFjxx;
import www.wmx.com.xssc.domain.doc.kjjbj.RbtKjjlKjjbjFjxx;
import www.wmx.com.xssc.domain.mb.RbtKjjlMbJcyjRank;
import www.wmx.com.xssc.domain.mb.RbtKjjlMbJcyjj;
import www.wmx.com.xssc.domain.mb.RbtKjjlMbTy;
import www.wmx.com.xssc.domain.vo.WcryShortXM;
import www.wmx.com.xssc.domain.vo.extract.BaseMatchResult;
import www.wmx.com.xssc.domain.vo.extract.ExtractArticle;
import www.wmx.com.xssc.domain.vo.extract.request.LWRequest;
import www.wmx.com.xssc.domain.vo.request.RequestPicture;
import www.wmx.com.xssc.domain.vo.response.ResponsePicture;
import www.wmx.com.xssc.domain.vo.response.lw.ContainResponse;
import www.wmx.com.xssc.service.fj.IRbtScfjMbService;
import www.wmx.com.xssc.service.fj.IZtComUploadFileOriginService;
import www.wmx.com.xssc.service.fj.IZtComUploadFileService;
import www.wmx.com.xssc.service.jcyjj.IRbtKjjlJcyjjFjxxService;
import www.wmx.com.xssc.service.jcyjj.IRbtKjjlJcyjjJbxxService;
import www.wmx.com.xssc.service.jsfmj.IRbtKjjlJsfmjFjxxService;
import www.wmx.com.xssc.service.kjjbj.IRbtKjjlKjjbjFjxxService;
import www.wmx.com.xssc.util.common.MbReadUtil;
import www.wmx.com.xssc.util.common.NameConvertUtil;
import www.wmx.com.xssc.util.common.WcrReadUtil;
import www.wmx.com.xssc.util.enumUtil.CgType;
import www.wmx.com.xssc.util.enumUtil.CgjlType;
import www.wmx.com.xssc.util.pdf.PDF;
import www.wmx.com.xssc.util.tptq.ImageExtractionUtil;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static www.wmx.com.xssc.xm.Similarity.pinyinSimilarity;

/**
 * @author Zhenyao.Diao
 * @create 2024/9/29 10:39
 * @description
 */
@Slf4j
@Data
@Component
public class ArticleProcessUtil {

    /**
     * 列举类型所有的成果奖励的基本信息业务类：
     */
    @Resource(description = "基础研究奖的基本信息：")
    private IRbtKjjlJcyjjJbxxService jcyjjJbxxService;
    @Resource
    private MbReadUtil mbReadUtil;
    /**
     * 所有当前年度的项目中涉及的研究人员和项目的信息：
     */
    @Resource
    private WcrReadUtil wcrReadUtil;
    @Resource(description = "附件的类型枚举")
    private IRbtScfjMbService scfjMbService;
    //论文附件的所有的类型和名称：
    List<RbtScfjMb> scfjJcyjjLWMbList;
    List<RbtScfjMb> scfjKjjbjjLWMbList;
    List<RbtScfjMb> scfjJsfmjLWMbList;
    @Resource(description = "基础研究附件信息")
    private IRbtKjjlJcyjjFjxxService jcyjjFjxxService;
    @Resource(description = "技术发明奖附件信息")
    private IRbtKjjlJsfmjFjxxService jsfmjFjxxService;
    @Resource(description = "科技进步奖附件信息")
    private IRbtKjjlKjjbjFjxxService kjjbjFjxxService;

    @Resource
    private IZtComUploadFileService uploadFileService;
    @Resource
    private IZtComUploadFileOriginService uploadFileOriginService;

    @Resource(description = "论文图片提取工具")
    private ImageExtractionUtil imageExtractionUtil;

    // 作者排名：
    private RbtKjjlMbJcyjRank kjjlMbJcyjRank;
    //contains:   0、1、2
    private RbtKjjlMbTy rbtKjjlMbTyLW;
    // 基础研究奖根据等级要求论文的信息：
    private List<RbtKjjlMbJcyjj> kjjlMbJcyjjsList;
    private static final Pattern pattern = Pattern.compile("[\\u4e00-\\u9fa5]+");
    private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    private String basePath;

    public void init() {
        this.mbReadUtil.init();
        this.scfjJcyjjLWMbList = scfjMbService.lambdaQuery()
                .eq(RbtScfjMb::getYwlx, "基础研究奖")
                .eq(RbtScfjMb::getWjlx, "论文").list();
        this.scfjKjjbjjLWMbList = scfjMbService.lambdaQuery()
                .eq(RbtScfjMb::getYwlx, "科技进步奖")
                .eq(RbtScfjMb::getWjlx, "论文").list();
        this.scfjJsfmjLWMbList = scfjMbService.lambdaQuery()
                .eq(RbtScfjMb::getYwlx, "技术发明奖")
                .eq(RbtScfjMb::getWjlx, "论文").list();
        this.kjjlMbJcyjRank = this.mbReadUtil.getKjjlMbJcyjRank();
        this.kjjlMbJcyjjsList = this.mbReadUtil.getKjjlMbJcyjjsList();
        List<RbtKjjlMbTy> kjjlMbTyList = this.mbReadUtil.getKjjlMbTyList();
        for (RbtKjjlMbTy mbTy : kjjlMbTyList) {
            if (mbTy.getId().equals(CgType.LW.getCode())) {
                this.rbtKjjlMbTyLW = mbTy;
                break;
            }
        }

        try {
            Properties properties = new Properties();
            // 读取my.properties配置文件到输入流中
            InputStream inputStream = PDF.class.getResourceAsStream("/config.properties");
            // 从输入流中加载属性列表
            properties.load(inputStream);
            this.basePath = properties.getProperty("file.upload.path");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * private IZtComUploadFileService uploadFileService;
     * private IZtComUploadFileOriginService uploadFileOriginService;
     * <p>
     * ZtComUploadFile
     * ZtComUploadFileOrigin
     */
    public String getArticlePath(LWRequest lwRequest) {
        String path = null;
        String FJID = null;
        if (lwRequest.getCgjlType() == CgjlType.JCYJJ.getCode()) {
            RbtKjjlJcyjjFjxx jcyjjFjxx = jcyjjFjxxService.lambdaQuery()
                    .eq(RbtKjjlJcyjjFjxx::getKjjlJcyjjId, lwRequest.getJbxxID())
                    .eq(RbtKjjlJcyjjFjxx::getWjlx, "论文")
                    .eq(RbtKjjlJcyjjFjxx::getWjmc, "论文题目作者裁剪")
                    .one();
            if (jcyjjFjxx == null) return null;
            FJID = jcyjjFjxx.getFjId();
            ZtComUploadFile uploadFile = uploadFileService.lambdaQuery()
                    .eq(ZtComUploadFile::getId, FJID)
                    .one();
            if (uploadFile == null) return null;
            ZtComUploadFileOrigin uploadFileOrigin = uploadFileOriginService.lambdaQuery()
                    .eq(ZtComUploadFileOrigin::getId, uploadFile.getFileMd5())
                    .one();
            if (uploadFileOrigin == null || uploadFileOrigin.getFilePath().isEmpty()) {
                return null;
            }
            path = uploadFileOrigin.getFilePath();
        } else if (lwRequest.getCgjlType() == CgjlType.JSFMJ.getCode()) {
            RbtKjjlJsfmjFjxx jsfmjFjxx = jsfmjFjxxService.lambdaQuery()
                    .eq(RbtKjjlJsfmjFjxx::getKjjlJsfmjId, lwRequest.getJbxxID())
                    .eq(RbtKjjlJsfmjFjxx::getWjlx, "论文")
                    .eq(RbtKjjlJsfmjFjxx::getWjmc, "论文题目作者裁剪")
                    .one();
            if (jsfmjFjxx == null) return null;
            FJID = jsfmjFjxx.getFjId();
            ZtComUploadFile uploadFile = uploadFileService.lambdaQuery()
                    .eq(ZtComUploadFile::getId, FJID)
                    .one();
            if (uploadFile == null) return null;
            ZtComUploadFileOrigin uploadFileOrigin = uploadFileOriginService.lambdaQuery()
                    .eq(ZtComUploadFileOrigin::getId, uploadFile.getFileMd5())
                    .one();
            if (uploadFileOrigin == null || uploadFileOrigin.getFilePath().isEmpty()) {
                return null;
            }
            path = uploadFileOrigin.getFilePath();
        } else if (lwRequest.getCgjlType() == CgjlType.KJJBJ.getCode()) {
            RbtKjjlKjjbjFjxx kjjbjFjxx = kjjbjFjxxService.lambdaQuery()
                    .eq(RbtKjjlKjjbjFjxx::getKjjlKjjbjId, lwRequest.getJbxxID())
                    .eq(RbtKjjlKjjbjFjxx::getWjlx, "论文")
                    .eq(RbtKjjlKjjbjFjxx::getWjmc, "论文题目作者裁剪")
                    .one();
            if (kjjbjFjxx == null) return null;
            FJID = kjjbjFjxx.getFjId();
            ZtComUploadFile uploadFile = uploadFileService.lambdaQuery()
                    .eq(ZtComUploadFile::getId, FJID)
                    .one();
            if (uploadFile == null) return null;
            ZtComUploadFileOrigin uploadFileOrigin = uploadFileOriginService.lambdaQuery()
                    .eq(ZtComUploadFileOrigin::getId, uploadFile.getFileMd5())
                    .one();
            if (uploadFileOrigin == null || uploadFileOrigin.getFilePath().isEmpty()) {
                return null;
            }
            path = uploadFileOrigin.getFilePath();
        }
        if(!ImageExtractionUtil.isImageFile(path,basePath)){
            return null;
        }
        return this.basePath + path;
    }

    public ResponsePicture extractPicture(LWRequest lwRequest) {
        RequestPicture requestPicture = new RequestPicture();
        requestPicture.setFilePath(lwRequest.getFilePath());
        ResponsePicture responsePicture = null;
        try {
            responsePicture = imageExtractionUtil.sendFormPost(requestPicture);
        } catch (Exception e) {
            responsePicture = null;
            log.error(e.getMessage());
        }
        return responsePicture;
    }

    public BaseMatchResult matchProcess(LWRequest lwRequest) {
        //首先处理论文的截图部分的具体地址信息：
        String articlePath = getArticlePath(lwRequest);
//        System.out.println("articlePath = " + articlePath);
        lwRequest.setFilePath(articlePath);
//        lwRequest.setFilePath("/root/OCR_Application/ocr_test_images/test3.png");//测试用路径
//        lwRequest.setFilePath("/home/user/workspace/test3.png");//测试时文件路径
        //只有基础研究奖才有作者排名的限制：
        lwRequest.setAuthorRankLimit(this.mbReadUtil.getKjjlMbJcyjRank().getZzpm());
        BaseMatchResult result = new BaseMatchResult();
        List<String> failReason = new ArrayList<>();
        String lwmcEnroll = lwRequest.getLwtm();
        if(articlePath!=null){
            ResponsePicture responsePicture = extractPicture(lwRequest);
            if(responsePicture!= null) {
                lwRequest.setPlainText(responsePicture.getData());
            }
        }else {
            failReason.add("论文题目作者裁剪图片不存在请重新上传");
        }
        LocalDateTime xmBeginTimeEnroll = lwRequest.getXmBeginTime();
        LocalDateTime xmEndTimeEnroll = lwRequest.getXmEndTime();
        int authorRankLimit = kjjlMbJcyjRank.getZzpm();
        //基础研究将登记的作者排名：
        int rankEnroll = 0;
        //根据上面的排名获取的作者的姓名：
        String authorEnroll = null;
        if (lwRequest.getCgjlType() == CgjlType.JCYJJ.getCode()) {
            rankEnroll = lwRequest.getZzpm();
            List<String> lwRequestAuthorEnroll = lwRequest.getAuthorEnroll();
            if (lwRequestAuthorEnroll == null || lwRequestAuthorEnroll.isEmpty() || rankEnroll >= lwRequestAuthorEnroll.size()) {
                failReason.add("论文作者排名不匹配：根据排名未能找到对应作者");
                failReason.add("完成人不匹配，未能找到论文登记作者");
            } else {
                authorEnroll = lwRequestAuthorEnroll.get(rankEnroll);
            }

        }
        int type = 0;
        boolean wcrMatchResult = false;
        boolean rankLimitMatchResult = false;
        boolean dateMatchResult;
        if (containsNoChinese(lwmcEnroll)) {
            type = 1;
        }
        if(authorEnroll!=null && articlePath!=null && lwRequest.getPlainText()!=null){
            //这是从论文中提取出来的内容：
            ExtractArticle extractArticle = processPatent(lwRequest, type);
            if(extractArticle!=null && extractArticle.getLwzz()!=null) {
                List<String> lwzzList = extractArticle.getLwzz();
                // 1.论文完成人一员的审查
                wcrMatchResult = wcrMatch(lwzzList, type, authorEnroll, lwRequest.getCgjlType(), lwRequest.getJbxxID());
                //3、作者排名的审查：
                if (lwRequest.getCgjlType() == CgjlType.JCYJJ.getCode()) {
                    rankLimitMatchResult = wcrRankLimitMatch(lwzzList, type, authorEnroll, authorRankLimit, rankEnroll);
                }
            }
        }
        //2、时间的审查：
        dateMatchResult = dateMatch(xmBeginTimeEnroll, xmEndTimeEnroll, lwRequest);

        //4. 论文附件的审查：
        List<String> failReasonFJ = FJCheck(lwRequest);

        if (!dateMatchResult) {
            result.setSuccess(false);
            failReason.add("时间不匹配： " + lwRequest.getFbny().format(DATE_FORMAT) + " 论文发表时间并未在项目起始时间段内");
        }
        if (!wcrMatchResult && authorEnroll != null) {
            result.setSuccess(false);
            failReason.add("完成人不匹配： " + authorEnroll + " 并非是论文完成人中的一员");
        }
        if (lwRequest.getCgjlType() == CgjlType.JCYJJ.getCode() && !rankLimitMatchResult && authorEnroll != null) {
            result.setSuccess(false);
            failReason.add("论文作者排名不匹配： " + authorEnroll + " 并非是论文的前 " + authorRankLimit + "作者");
        }
        if (lwRequest.getCgjlType() == CgjlType.JCYJJ.getCode() && lwRequest.getTycs() <= 0) {
            result.setSuccess(false);
            failReason.add("论文他引次数为0不符合要求");
        }
        if (failReasonFJ != null && failReasonFJ.size() > 0) {
            failReason.addAll(failReasonFJ);
        }
        result.setFailReason(failReason);
        return result;
    }


    /**
     * 论文的附件的审查：
     */
    public List<String> FJCheck(LWRequest lwRequest) {
        List<String> failReason = new ArrayList<>();
        if (lwRequest.getCgjlType() == CgjlType.JCYJJ.getCode()) {
            for (RbtScfjMb scfjMb : scfjJcyjjLWMbList) {
                List<RbtKjjlJcyjjFjxx> fjxx = jcyjjFjxxService.lambdaQuery()
                        .eq(RbtKjjlJcyjjFjxx::getKjjlJcyjjId, lwRequest.getJbxxID())
                        .eq(RbtKjjlJcyjjFjxx::getWjmc, scfjMb.getWjmc())
                        .eq(RbtKjjlJcyjjFjxx::getWjlx, "论文")
                        .list();
                if (fjxx == null || fjxx.isEmpty()) {
                    failReason.add("论文缺少附件:  " + scfjMb.getWjmc() + " ");
                }
            }
        } else if (lwRequest.getCgjlType() == CgjlType.JSFMJ.getCode()) {
            for (RbtScfjMb scfjMb : scfjJsfmjLWMbList) {
                List<RbtKjjlJsfmjFjxx> fjxx = jsfmjFjxxService.lambdaQuery()
                        .eq(RbtKjjlJsfmjFjxx::getKjjlJsfmjId, lwRequest.getJbxxID())
                        .eq(RbtKjjlJsfmjFjxx::getWjmc, scfjMb.getWjmc())
                        .eq(RbtKjjlJsfmjFjxx::getWjlx, "论文")
                        .list();
                if (fjxx == null || fjxx.isEmpty()) {
                    failReason.add("论文缺少附件:  " + scfjMb.getWjmc() + " ");
                }
            }
        } else if (lwRequest.getCgjlType() == CgjlType.KJJBJ.getCode()) {
            for (RbtScfjMb scfjMb : scfjKjjbjjLWMbList) {
                List<RbtKjjlKjjbjFjxx> fjxx = kjjbjFjxxService.lambdaQuery()
                        .eq(RbtKjjlKjjbjFjxx::getKjjlKjjbjId, lwRequest.getJbxxID())
                        .eq(RbtKjjlKjjbjFjxx::getWjmc, scfjMb.getWjmc())
                        .eq(RbtKjjlKjjbjFjxx::getWjlx, "论文")
                        .list();
                if (fjxx == null || fjxx.isEmpty()) {
                    failReason.add("论文缺少附件:  " + scfjMb.getWjmc() + " ");
                }
            }
        }
        return failReason;
    }


    //验证完成人是否是前几名中的一员：
    public boolean wcrRankLimitMatch(List<String> lwzzList, int type, String authorEnroll, int authorRankLimit, int rankEnroll) {
        //1.首先验证是否是authorRankLimit限制的前几名：
        boolean flag = false;
        int size = Math.min(authorRankLimit, lwzzList.size());
        for (int i = 0; i < size; i++) {
            if (type == 0) {
                String name = lwzzList.get(i);
                name = name.replaceAll(" ", "");
                String pinyinName = NameConvertUtil.convertToPinyin(name);
                String enrollName = NameConvertUtil.convertToPinyin(authorEnroll);
                double similarity = pinyinSimilarity(pinyinName, enrollName);
                if (pinyinName.equals(enrollName) || similarity >= 0.8) {
                    flag = true;
                }
            } else {
                String name = lwzzList.get(i);
                name = name.replaceAll(" ", "");
                double similarity = pinyinSimilarity(name, authorEnroll);
                if (name.equals(authorEnroll) || similarity >= 0.8) {
                    flag = true;
                }
            }
        }
        if (!flag) return false;
        //验证是否是限定的排名
        if (type == 0) {
            String name = lwzzList.get(rankEnroll);
            name = name.replaceAll(" ", "");
            String pinyinName = NameConvertUtil.convertToPinyin(name);
            String enrollName = NameConvertUtil.convertToPinyin(authorEnroll);
            double similarity = pinyinSimilarity(pinyinName, enrollName);
            if (pinyinName.equals(enrollName) || similarity >= 0.8) {
                return true;
            } else return false;
        } else {
            String name = lwzzList.get(rankEnroll);
            name = name.replaceAll(" ", "");
            return pinyinSimilarity(name, authorEnroll) >= 0.8;
        }
    }

    /**
     * 验证完成人是否是论文作者中的一员：
     *
     * @param lwzzList     图片提取出来的作者的信息
     * @param type
     * @param authorEnroll
     * @param cgjlType
     * @return
     */
    public boolean wcrMatch(List<String> lwzzList, int type, String authorEnroll, int cgjlType, String jbxxId) {
        //基础研究奖进行单个人员的比对
        if (cgjlType == CgjlType.JCYJJ.getCode()) {
            if (type == 0) {
                for (String name : lwzzList) {
                    name = name.replaceAll(" ", "");
                    String pinyinName = NameConvertUtil.convertToPinyin(name);
                    String enrollName = NameConvertUtil.convertToPinyin(authorEnroll);
                    double similarity = pinyinSimilarity(pinyinName, enrollName);
                    if (pinyinName.equals(enrollName) || similarity >= 0.8) {
                        return true;
                    }
                }
            } else {
                for (String name : lwzzList) {
                    name = name.replaceAll(" ", "");
                    double similarity = pinyinSimilarity(name, authorEnroll);
                    if (name.equals(authorEnroll) || similarity >= 0.8) {
                        return true;
                    }
                }
            }
            // 其余的奖项需要所有项目参与人员的比对
        } else {
            List<WcryShortXM> wcryShortXMS = wcrReadUtil.getWcryFilterByTypeAndId(cgjlType, jbxxId);
            for (String name : lwzzList) {
                name = name.replaceAll(" ", "");
                String pinyinName = NameConvertUtil.convertToPinyin(name);
                for (WcryShortXM wcryShortXM : wcryShortXMS) {
                    String enrollName = NameConvertUtil.convertToPinyin(wcryShortXM.getXm().replaceAll(" ", ""));
                    double similarity = pinyinSimilarity(pinyinName, enrollName);
                    if (pinyinName.equals(enrollName) || similarity >= 0.8) {
                        return true;
                    }
                }
            }
            return false;
        }
        return false;
    }

    //论文完成时间的审查：
    public boolean dateMatch(LocalDateTime begin, LocalDateTime end, LWRequest request) {

//        LocalDateTime fbsj = LocalDateTime.from(request.getFbny());
        LocalDateTime fbsj = request.getFbny().atStartOfDay();
        return fbsj.isAfter(begin) && fbsj.isBefore(end);
    }

    /**
     * @param lwRequest:{用户填写的论文名称 lwmc ，需要处理的请求文本 plainText }
     * @param type                 0：中文；1：英文
     * @return
     */
    public ExtractArticle processPatent(LWRequest lwRequest, Integer type) {
        if (type.equals(0)) {
            return processChinese(lwRequest);
        } else
            return processEnglish(lwRequest);
    }

    /**
     * 处理中文的论文题目：
     *
     * @param lwRequest
     * @return
     */
    public ExtractArticle processChinese(LWRequest lwRequest) {
        ExtractArticle response = new ExtractArticle();
        String lwmcOrigin = lwRequest.getLwtm();
        String request = lwRequest.getPlainText();
        String wcrStr  = null;
        String twoCharStr = null;
        if(lwmcOrigin.length()>2) {
            twoCharStr = lwmcOrigin.substring(lwmcOrigin.length() - 2);
        }
        if(twoCharStr!=null && request.indexOf(twoCharStr)!=-1) {
            int wcrIndexBegin = request.indexOf(twoCharStr) + 2;
            wcrStr = request.substring(wcrIndexBegin);
        }
        if(twoCharStr==null || wcrStr==null){
            return null;
        }
        String noNewLines = wcrStr.replaceAll("[\\r\\n]+", " ");
        // 然后，将多个连续的空格替换为一个空格
        wcrStr = noNewLines.replaceAll("\\s+", " ");
        String[] wcrNameSplit = wcrStr.split("[,，、]+");
        List<String> lwwcrList = new ArrayList<>();
        for (String sName : wcrNameSplit) {
            // 使用正则表达式匹配所有汉字
            // 使用Pattern和Matcher类来查找所有匹配的汉字
            Matcher matcher = pattern.matcher(sName);
            // 创建一个StringBuilder来存储所有找到的汉字
            StringBuilder chineseCharacters = new StringBuilder();
            while (matcher.find()) {
                // 将找到的汉字添加到StringBuilder中
                chineseCharacters.append(matcher.group()).append(" ");
            }
            // 去除最后一个多余的空格（如果有的话）
            if (chineseCharacters.length() > 0 && chineseCharacters.charAt(chineseCharacters.length() - 1) == ' ') {
                chineseCharacters.deleteCharAt(chineseCharacters.length() - 1);
            }
            lwwcrList.add(chineseCharacters.toString());
        }
//        lwwcrList.forEach(System.out::println);
        response.setLwmc(lwmcOrigin);
        response.setType(0);
        response.setLwzz(lwwcrList);
        return response;
    }


    /**
     * 英文名字需要进行特殊的处理，因为可能涉及到分隔符漏掉的情形:
     *
     * @param lwRequest
     * @return
     */
    public ExtractArticle processEnglish(LWRequest lwRequest) {
        ExtractArticle response = new ExtractArticle();
        String lwmcOrigin = lwRequest.getLwtm();
        String request = lwRequest.getPlainText();
        String twoCharStr = lwmcOrigin;
        int wcrIndexBegin = lwmcOrigin.length();
        //TODO 数据库中论文名称长度小于4时出现字符串索引越界
        if(lwmcOrigin.length() >=4) {
            twoCharStr = lwmcOrigin.substring(lwmcOrigin.length() - 4);
            if(request.indexOf(twoCharStr)!=-1) {
                wcrIndexBegin = request.indexOf(twoCharStr) + 4;
            }
        }
        String wcrStr = request.substring(wcrIndexBegin);
        if(wcrStr!=null) {
            wcrStr = wcrStr.substring(findFirstUppercase(wcrStr));
        }else {
            return null;
        }
        //接下来需要处理英文的名字：
        int num = 0;
        List<String> nameList = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < wcrStr.length(); i++) {
            char c = wcrStr.charAt(i);
            if (c == 'd' && sb.length() > 2) {
                String subTwoChar = sb.substring(sb.length() - 2);
                if (subTwoChar.equals("an")) {
                    String name = clearName(sb.toString().substring(0, sb.length() - 2));
                    if (name != null && name.length() > 0) {
                        nameList.add(name);
                    }
                    sb = new StringBuilder();
                    num = 0;
                    continue;
                }
            }
            if (c == ' ') {
                if (num == 1) {
                    String name = clearName(sb.toString());
                    if (name != null && name.length() > 0) {
                        nameList.add(name);
                    }
                    sb = new StringBuilder();
                    num = 0;
                } else {
                    if (sb.length() > 0) {
                        num++;
                    }
                    sb.append(c);
                }
            } else if (c == ',' || c == '，' || (sb.length() > 0 && isLetterChar(sb.charAt(sb.length() - 1)) && !isUpper(sb.charAt(sb.length() - 1)) && isUpper(c))) {
                if (num == 1) {
                    String name = clearName(sb.toString());
                    if (name != null && name.length() > 0)
                        nameList.add(name);
                    sb = new StringBuilder();
                    num = 0;
                } else {
                    num++;
                }
                if (c != ',' && c != '，') {
                    sb.append(c);
                }
            } else if (c == '-') {
                sb.append(" ");
            } else if (isLetterChar(c)) {
                sb.append(c);
            }
            if (i == wcrStr.length() - 1) {
                nameList.add(clearName(sb.toString()));
                break;
            }
        }
        response.setLwzz(nameList);
        response.setType(1);
        response.setLwmc(lwmcOrigin);
        return response;
    }

    private String clearName(String name) {
        name = name.trim();
        if (name.isEmpty() || name.length() == 1 && name.equals(" "))
            return null;
        String[] names = name.split(" ");
        name = "";
        for (int i = 0; i < names.length; i++) {
            String nameS = names[i];
            String[] nameStr = getDXNum(nameS);
            if (i != names.length - 1) {
                for (String s : nameStr) {
                    name += (s.toLowerCase() + " ");
                }
            } else {
                for (int j = 0; j < nameStr.length; j++) {
                    if (j != nameStr.length - 1) {
                        name += (nameStr[j].toLowerCase() + " ");
                    } else {
                        name += nameStr[j].toLowerCase();
                    }
                }
            }
        }
        return name;
    }

    public String[] getDXNum(String name) {
        int xNum = 0, dNum = 0;
        for (int i = 0; i < name.length(); i++) {
            char c = name.charAt(i);
            if (c >= 'a' && c <= 'z')
                xNum++;
            else dNum++;
        }
        if (xNum == 0 || dNum == 0 || dNum == 1) return new String[]{name.toLowerCase()};
        for (int i = 0; i < name.length(); i++) {
            char c = name.charAt(i);
            if (c >= 'a' && c <= 'z') {
                String str1 = name.substring(0, i - 1);
                String str2 = name.substring(i - 1);
                return new String[]{str1, str2};
            }
        }
        return null;
    }

    public boolean isUpper(char c) {
        return c >= 'A' && c <= 'Z';
    }

    public boolean isLetterChar(char c) {
        return c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z';
    }

    public int findFirstUppercase(String str) {
        for (int i = 0; i < str.length(); i++) {
            if (Character.isUpperCase(str.charAt(i))) {
                return i; // 返回第一个大写字母的索引
            }
        }
        return -1; // 如果没有找到大写字母，则返回-1
    }

    // 判断字符串是否不含有中文
    public boolean containsNoChinese(String input) {
        if (input == null || input.isEmpty()) {
            return true; // 空字符串不包含中文
        }

        for (char c : input.toCharArray()) {
            // 检查字符是否在中文范围内
            if (isChineseCharacter(c)) {
                return false; // 一旦发现中文字符，返回false
            }
        }
        return true; // 遍历完所有字符，未发现中文字符，返回true
    }

    // 判断单个字符是否是中文字符
    private boolean isChineseCharacter(char c) {
        // 基本区
        if (c >= '\u4E00' && c <= '\u9FFF') {
            return true;
        }
        return false;
    }

    /*    public static void main(String[] args) {
     *//* String plainText = "煤岩类型对煤储层吸附/解吸特征影响及实践意义\n" +
                "以保德区块为例\n" +
                "侯伟1²，徐凤银1²，张雷1²，张伟²，孟艳军3，刘其虎²，李永臣²,\n" +
                "樊洪波²，王虹雅1²，张双源1²，张文²";
        String lwmc = "煤岩类型对煤储层吸附/解吸特征影响及实践意义\n" +
                "以保德区块为例";
        int type = 0;
        LWRequest requestNew = new LWRequest();
        requestNew.setLwmc(lwmc);
        requestNew.setPlainText(plainText);

        ExtractArticle extractArticle = ArticleProcessUtil.processPatent(requestNew, 0);
        System.out.println(extractArticle);*//*

        String plainText = "Geological Model ReconstructionofHorizontalWell\n" +
                "based on High-precision3D Seismic and its Application\n" +
                "Effectl\n" +
                "ZHANG FengJIA Xue-cheng',TONG Jiang-nan²,JIANG Hong-\n" +
                "yu'ZHANGXiao-mingand SUN Pei";
        String lwmc = "Geological Model ReconstructionofHorizontalWell\\n\" +\n" +
                "                \"based on High-precision3D Seismic and its Application\\n\" +\n" +
                "                \"Effect";
        int type = 1;
        LWRequest requestNew = new LWRequest();
        requestNew.setLwtm(lwmc);
        requestNew.setPlainText(plainText);

//        ExtractArticle extractArticle = ArticleProcessUtil.processPatent(requestNew, 1);
//        System.out.println(extractArticle);
        double v = pinyinSimilarity("李宁", "黎宁");
        System.out.println(v);
    }*/

}

